<template>
  <el-dialog
    title="选择管材标准"
    :visible.sync="visible"
    width="60%"
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <div class="pipe-standard-container">
      <div class="search-action-bar">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="部件名称">
            <el-input
              v-model="searchForm.pipeName"
              placeholder="请输入部件名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="管道规格">
            <el-input
              v-model="searchForm.pipeSpecification"
              placeholder="请输入管道规格"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        max-height="400"
        border
        stripe
        @selection-change="handleSelectionChange"
        :row-key="(row) => row.pipeStaId"
        ref="standardTable"
      >
        <!-- 单选勾选框 -->
        <el-table-column type="selection" width="55" :selectable="() => true" />
        <el-table-column prop="pipeStaId" label="管材标准ID" />
        <el-table-column prop="pipeName" label="部件名称" />
        <el-table-column prop="pipeSpecification" label="管道规格" />
        <el-table-column prop="pipeMaterial" label="管道材料" />
        <el-table-column prop="pipeValue" label="管道厚度标准值" />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          :formatter="formatDate"
        />
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-bar" style="margin-top: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageDto.page"
          :page-sizes="[5, 10, 20]"
          :page-size="pageDto.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>

      <!-- 确认/取消按钮 -->
      <div style="text-align: right; margin-top: 10px">
        <el-button type="danger" @click="handleClose">取消</el-button>
        <el-button
          type="success"
          @click="confirmSelect"
          :disabled="selectedRows.length !== 1"
        >
          确认选择
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "PipeStandardSelector",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      searchForm: {},
      pageDto: { page: 1, size: 10, pipeStandard: {} },
      total: 0,
      tableData: [],
      selectedRows: [],
      historyIds: JSON.parse(localStorage.getItem("pipeStaHistoryIds")) || [],
    };
  },
  methods: {
    formatDate(row, column) {
      const date = row[column.property];
      return date ? new Date(date).toLocaleString() : "";
    },
    handleSizeChange(val) {
      this.pageDto.size = val;
      this.queryByPage();
    },
    handleCurrentChange(val) {
      this.pageDto.page = val;
      this.queryByPage();
    },
    handleQuery() {
      this.pageDto.pipeStandard.pipeName = this.searchForm.pipeName;
      this.pageDto.pipeStandard.pipeSpecification =
        this.searchForm.pipeSpecification;
      this.pageDto.page = 1;
      this.queryByPage();
    },
    resetQuery() {
      this.searchForm = {};
      this.pageDto = { page: 1, size: 10, pipeStandard: {} };
      this.queryByPage();
    },
    queryByPage() {
      this.$api.pipeStandardApi
        .queryByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "查询失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "网络异常，请重试",
          });
        });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    confirmSelect() {
      if (this.selectedRows.length !== 1) {
        this.$notify.warning({
          title: "提示",
          message: "请选择**一条**数据",
        });
        return;
      }
      const selectedRow = this.selectedRows[0];
      //整行数据传递
      this.$emit("selected", selectedRow);
      if (!this.historyIds.includes(selectedRow.pipeStaId)) {
        this.historyIds.push(selectedRow.pipeStaId);
        localStorage.setItem(
          "pipeStaHistoryIds",
          JSON.stringify(this.historyIds)
        );
      }
      this.handleClose();
    },
    handleClose() {
      this.selectedRows = [];
      this.$refs.standardTable.clearSelection();
      this.$emit("update:visible", false);
    },
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.queryByPage();
      }
    },
  },
};
</script>

<style scoped>
.pipe-standard-container {
  padding: 10px;
}
</style>
